<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工作序号" prop="serial">
        <el-input
          v-model="queryParams.serial"
          placeholder="请输入工作序号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入工作标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责部门" prop="department">
        <el-input
          v-model="queryParams.department"
          placeholder="请输入负责部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择工作状态" clearable>
          <el-option
            v-for="dict in dict.type.work_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:work:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:work:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:work:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:work:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工作序号" align="center" prop="serial" width="120" />
      <el-table-column label="工作标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="负责部门" align="center" prop="department" width="120" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成进度" align="center" prop="progress" width="100">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.progress" :color="getProgressColor(scope.row.progress)"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.work_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:work:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:work:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改重点工作对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入工作标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责部门" prop="department">
              <el-input v-model="form.department" placeholder="请输入负责部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="工作描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入工作描述" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                placeholder="选择开始时间"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                placeholder="选择结束时间"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="完成进度" prop="progress">
              <el-input-number v-model="form.progress" :min="0" :max="100" placeholder="完成进度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择工作状态">
                <el-option
                  v-for="dict in dict.type.work_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="相关图片" prop="images">
          <image-upload v-model="form.images"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看重点工作详情对话框 -->
    <el-dialog title="重点工作详情" :visible.sync="viewOpen" width="800px" append-to-body>
      <div v-if="viewData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工作序号">{{ viewData.serial }}</el-descriptions-item>
          <el-descriptions-item label="工作标题">{{ viewData.title }}</el-descriptions-item>
          <el-descriptions-item label="负责部门">{{ viewData.department }}</el-descriptions-item>
          <el-descriptions-item label="工作状态">
            <dict-tag :options="dict.type.work_status" :value="viewData.status"/>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ parseTime(viewData.startTime, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ parseTime(viewData.endTime, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="完成进度" :span="2">
            <el-progress :percentage="viewData.progress" :color="getProgressColor(viewData.progress)"></el-progress>
          </el-descriptions-item>
          <el-descriptions-item label="工作描述" :span="2">{{ viewData.description }}</el-descriptions-item>
          <el-descriptions-item label="相关图片" :span="2" v-if="viewData.images && viewData.images.length > 0">
            <el-image
              v-for="(image, index) in viewData.images"
              :key="index"
              :src="getImageUrl(image)"
              :preview-src-list="getPreviewImages(viewData.images)"
              style="width: 100px; height: 100px; margin-right: 10px;"
              fit="cover"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
                <div>加载失败</div>
              </div>
            </el-image>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ viewData.remark }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWork, getWork, delWork, addWork, updateWork } from "@/api/system/work";

export default {
  name: "Work",
  dicts: ['work_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 重点工作表格数据
      workList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewOpen: false,
      // 查看数据
      viewData: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serial: null,
        title: null,
        department: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "工作标题不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "工作描述不能为空", trigger: "blur" }
        ],
        department: [
          { required: true, message: "负责部门不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询重点工作列表 */
    getList() {
      this.loading = true;
      listWork(this.queryParams).then(response => {
        this.workList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serial: null,
        title: null,
        description: null,
        department: null,
        startTime: null,
        endTime: null,
        progress: 0,
        status: "pending",
        images: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加重点工作";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWork(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改重点工作";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewData = row;
      this.viewOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWork(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWork(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除重点工作编号为"' + ids + '"的数据项？').then(function() {
        return delWork(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/work/export', {
        ...this.queryParams
      }, `work_${new Date().getTime()}.xlsx`)
    },
    /** 获取进度条颜色 */
    getProgressColor(progress) {
      if (progress < 30) {
        return '#f56c6c';
      } else if (progress < 70) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    },
    /** 获取完整的图片URL */
    getImageUrl(image) {
      if (!image) return '';
      // 如果图片URL已经包含完整路径，直接返回
      if (image.startsWith('http') || image.startsWith('//')) {
        return image;
      }
      // 否则加上基础URL
      return process.env.VUE_APP_BASE_API + image;
    },
    /** 获取预览图片列表 */
    getPreviewImages(images) {
      if (!images || images.length === 0) return [];
      return images.map(image => this.getImageUrl(image));
    }
  }
};
</script>

<style scoped>
.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-slot i {
  font-size: 30px;
  margin-bottom: 8px;
}
</style>
